<?php
namespace auth;
use think\Cache;
use think\Config;
use base\date\Dates;
class Api{
    // 对象实例
    protected static $instance;
	
	// 密钥
    protected  $rangeTime = 300; // 服务器范围时间,单位为秒, 300 = 5分钟
	
	// 设置参数
    protected $options = [
    	[
    		'appkey'         => 'B0QEUmyvrPsN5glD',      			
        	'secret'          =>  '8COw7MRw9rWlAKWz8534WpVy2LVrQRmW',
    	],
    	[
    		'appkey'         => 'A941EZHA',      			
        	'secret'          =>  '4B79189440E162108405707D32EB5CCE',
    	],
    	[
    		'appkey'         => 'UC5YRY0I',      			
        	'secret'          =>  '7C826AF0CE5844BB379141A33DF3538A',
    	]
    ];


    // 初始化 参数
    protected function __construct($options = [])
    {
      
    }

    /**
     * 外部调用获取实列
     * @param array $options
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }
	
	
    /**
     * 获取oken值
     * @param String $user_id
     * @return array
     */
    public function getToken($data)
    {
    	$secret = $this->getSecret($data['appkey']);
		
    	if(!$secret){
    		$this->errorCode = 1002;
    		$this->errorInfo = "appkey 无效！";
    		return false;
    	}
		
		if( !$data['nonce'] ){
			$this->errorCode = 1001;
			$this->errorInfo = "nonce 无效！";
    		return false;
		}
		
		if( !$data['time'] ){
			$this->errorCode = 1003;
			$this->errorInfo = "time 时间戳无效！";
    		return false;
		}
		
		$time = abs( Dates::getMillisecond() - $data['time'] )  / 1000;
		if( $time > $this->rangeTime ){
			$this->errorCode = 1003;
			$this->errorInfo = "time 时间戳无效！";
    		return false;
		}
        
		return  strtoupper(md5($this->ascii($data).'&secret='.$secret));
    }

    /**
     * 验证Token
     * @param String 
     * @return array
     */
    public function checkToken($token)
    {
		$str = $this->getToken( request()->post() );
		if(!$str) return false;
    	if($token != $str ){
			$this->errorCode = 1004;
			$this->errorInfo = "token 无效";
    		return false;
    	}
    	return true;
    }

	// 获取密钥
	protected function getSecret($appkey){
	  	$str = '';
       	foreach ($this->options as $k=>$val){
           	if($val['appkey'] ==  $appkey) return $val['secret'];
       	}
        return $str;
	}
	
	// ASCII 码从小到大排序
	protected function ascii($params = array()){
	    if(!empty($params)){
	       $p =  ksort($params);
	       if($p){
	           $str = '';
	            foreach ($params as $k=>$val){
	               if($val) $str .= $k .'=' . $val . '&';
	            }
	           $strs = rtrim($str, '&');
	           return $strs;
	       }
	    }
	    return '';
	}
	
}
